/*******************************************************************************
* 版本声明：v1.0.0
* 类 名 称：AreaCalculation
* 创建日期：2021-03-31 17:08:28
* 作者名称：末零
* 功能描述：根据网格获取表面积和体积
* 修改记录：
* 
******************************************************************************/

using System;
using UnityEngine;

namespace LastZero.Utility
{
    /// <summary>
    /// 表面积、体积的计算
    /// </summary>
    public static class MeshExtend
    {
        /// <summary>
        /// 获取表面积
        /// </summary>
        /// <param name="obj">带有MeshFilter的物体</param>
        /// <param name="callbackError">错误回调</param>
        /// <returns>表面积</returns>
        public static float GetArea(this Transform obj, Action callbackError = null)
        {
            Mesh mesh = obj.GetComponent<MeshFilter>().mesh;
            if (mesh == null)
            {
                Debug.LogWarning("There is no 'MeshFilter' component!");
                callbackError?.Invoke();
                return -1;
            }

            Vector3[] vertices = mesh.vertices;
            Vector3 lossyScale = obj.lossyScale;

            float area = 0;
            for (int i = 0; i < mesh.subMeshCount; i++)
            {
                int[] triangles = mesh.GetTriangles(i);
                for (int j = 0; j < triangles.Length; j += 3)
                {
                    area += CalculateTriangleArea(vertices[triangles[j]], vertices[triangles[j + 1]], vertices[triangles[j + 2]], lossyScale);
                }
            }

            return area;
        }

        /// <summary>
        /// 计算三角形面积
        /// </summary>
        /// <param name="point1">顶点1</param>
        /// <param name="point2">顶点2</param>
        /// <param name="point3">顶点3</param>
        /// <returns>面积</returns>
        private static float CalculateTriangleArea(Vector3 point1, Vector3 point2, Vector3 point3, Vector3 lossyScale)
        {
            //计算缩放
            point1 = new Vector3(point1.x * lossyScale.x, point1.y * lossyScale.y, point1.z * lossyScale.z);
            point2 = new Vector3(point2.x * lossyScale.x, point2.y * lossyScale.y, point2.z * lossyScale.z);
            point3 = new Vector3(point3.x * lossyScale.x, point3.y * lossyScale.y, point3.z * lossyScale.z);

            //计算边长
            float l1 = (point2 - point1).magnitude;
            float l2 = (point3 - point2).magnitude;
            float l3 = (point1 - point3).magnitude;
            float p = (l1 + l2 + l3) * 0.5f;

            //计算面积  S=√[p(p-l1)(p-l2)(p-l3)]（p为半周长）
            return Mathf.Sqrt(p * (p - l1) * (p - l2) * (p - l3));
        }

        /// <summary>
        /// 获取体积
        /// </summary>
        /// <param name="obj">带有MeshFilter的物体</param>
        /// <param name="callbackError">错误回调</param>
        /// <returns></returns>
        public static float GetVolume(this Transform obj, Action callbackError = null)
        {
            Mesh mesh = obj.GetComponent<MeshFilter>().mesh;
            if (mesh == null)
            {
                Debug.LogWarning("There is no 'MeshFilter' component!");
                callbackError?.Invoke();
                return -1;
            }

            Vector3[] vertices = mesh.vertices;
            Vector3 lossyScale = obj.lossyScale;
            Vector3 o = GetCenter(vertices);

            float volume = 0;
            for (int i = 0; i < mesh.subMeshCount; i++)
            {
                int[] triangles = mesh.GetTriangles(i);
                for (int j = 0; j < triangles.Length; j += 3)
                {
                    volume += CalculateVolumeOfTriangle(vertices[triangles[j]], vertices[triangles[j + 1]], vertices[triangles[j + 2]], o, lossyScale);
                }
            }

            return Mathf.Abs(volume);
        }

        /// <summary>
        /// 获取中心点
        /// </summary>
        /// <param name="points">顶点</param>
        /// <returns>中心点</returns>
        private static Vector3 GetCenter(Vector3[] points)
        {
            Vector3 center = Vector3.zero;
            for (int i = 0; i < points.Length; i++)
            {
                center += points[i];
            }
            center = center / points.Length;
            return center;
        }

        /// <summary>
        /// 计算一个面和中心点组成三棱锥的体积
        /// </summary>
        /// <param name="point1">顶点1</param>
        /// <param name="point2">顶点2</param>
        /// <param name="point3">顶点3</param>
        /// <param name="center">中心点</param>
        /// <returns></returns>
        private static float CalculateVolumeOfTriangle(Vector3 point1, Vector3 point2, Vector3 point3, Vector3 center, Vector3 lossyScale)
        {
            //计算缩放
            point1 = new Vector3(point1.x * lossyScale.x, point1.y * lossyScale.y, point1.z * lossyScale.z);
            point2 = new Vector3(point2.x * lossyScale.x, point2.y * lossyScale.y, point2.z * lossyScale.z);
            point3 = new Vector3(point3.x * lossyScale.x, point3.y * lossyScale.y, point3.z * lossyScale.z);

            //向量
            Vector3 v1 = point1 - center;
            Vector3 v2 = point2 - center;
            Vector3 v3 = point3 - center;

            //计算体积
            //首先我们求以这三个向量为邻棱的平行六面体的面积
            //那就是（a×b）·c的绝对值
            //然后四面体的体积是平行六面体的六分之一
            //因为四面体的底是平行六面体的一半,而且要多乘一个三分之一
            float v = Vector3.Dot(Vector3.Cross(v1, v2), v3) / 6f;
            return v;
        }
    }
}